/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sd.chat;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Old
 */
public class ServerPinger extends Thread {

    private ServerManager myManager;
    private boolean shutdown = false;
    private int port;
    private int serverport;
    private String adress;
    private int ttl = 2;
    DatagramSocket socket;
    DatagramSocket socket2;

    public ServerPinger(ServerManager myManager, int port, int serport, String adress) {
        super("server pinger");
        this.myManager = myManager;
        this.port = port;
        this.serverport = serport;
        this.adress = adress;
    }

    public void createSocket() {
        try {
            socket = new DatagramSocket();
        } catch (SocketException e) {
            System.out.println("Error creating socket: " + e);
        }
    }

    public void createSocket(int port) {
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            System.out.println("Error creating socket: " + e);
        }
    }

    public String receivePing() throws SocketTimeoutException {
        /* Create packet for receiving the reply */
        byte recvBuf[] = new byte[1024];
        DatagramPacket recvPacket = new DatagramPacket(recvBuf, 1024);
        String reply = "";

        /* Read message from socket. */
        try {
            socket.receive(recvPacket);

            System.out.println("Received message from " + recvPacket.getAddress() + ":" + recvPacket.getPort());
            String recvMsg = new String(recvPacket.getData());
            reply = recvMsg;

        } catch (SocketTimeoutException e) {
            System.out.println("Error timeout socket: " + e);
        } catch (IOException e) {
            System.out.println("Error reading from socket: " + e);
        }
        return reply;
    }
    
    public ServerData receiveBackup(int length) throws SocketTimeoutException {
        /* Create packet for receiving the reply */
        byte recvBuf[] = new byte[length];
        DatagramPacket recvPacket = new DatagramPacket(recvBuf, length);
        ServerData reply = null;

        /* Read message from socket. */
        try {
            socket.receive(recvPacket);

            System.out.println("Received message from " + recvPacket.getAddress() + ":" + recvPacket.getPort());
            reply = (ServerData)myManager.getObjectFromBytes(recvPacket.getData());

        } catch (SocketTimeoutException e) {
            System.out.println("Error timeout socket: " + e);
        } catch (IOException e) {
            System.out.println("Error reading from socket: " + e);
        }
        return reply;
    }

    public void sendPing(String ping) {
        InetAddress host;
        try {
            socket.setSoTimeout(3000);

            host = InetAddress.getByName(adress);

            int port = ConfigsGerais.pingserverport;
            String message = ""+ping;


            /* Create a datagram packet addressed to the recipient */
            DatagramPacket packet = new DatagramPacket(message.getBytes(),
                    message.length(), host, port);

            /* Send the packet */
            socket.send(packet);
            System.out.println("Sent message to " + host + ":" + port);
        } catch (UnknownHostException ex) {
            Logger.getLogger(ServerPinger.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException e) {
            System.out.println("Error sending packet: " + e);
        }
    }

    public void sendBackupRequest(String msg) {
        InetAddress host;
        try {
            socket.setSoTimeout(3000);

            host = InetAddress.getByName(adress);

            int port = ConfigsGerais.pingserverport;
            String message = ""+msg;


            /* Create a datagram packet addressed to the recipient */
            DatagramPacket packet = new DatagramPacket(message.getBytes(),
                    message.length(), host, port);

            /* Send the packet */
            socket.send(packet);
            System.out.println("Sent message to " + host + ":" + port);
        } catch (UnknownHostException ex) {
            Logger.getLogger(ServerPinger.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException e) {
            System.out.println("Error sending packet: " + e);
        }
    }

    @Override
    public void run() {
        try {
            // TODO Auto-generated method stub
            DatagramSocket serverSocket = new DatagramSocket(9876);
            byte[] receiveData = new byte[1024];
            byte[] sendData = new byte[1024];
            while (!shutdown) {
                sendData = new byte[1024];
                DatagramPacket receivePacket = new DatagramPacket(receiveData,
                        receiveData.length);
                serverSocket.receive(receivePacket);
                String sentence = new String(receivePacket.getData());
                /*if (sentence != null && !sentence.equals("")) {
                    System.out.println(sentence);
                }*/
                byte[] backupServer = myManager.getBytes(myManager.getDb());
                sentence = ""+backupServer.length;
                InetAddress IPAddress = receivePacket.getAddress();
                int port = receivePacket.getPort();
                sendData = sentence.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(sendData,
                        sendData.length, IPAddress, port);
                serverSocket.send(sendPacket);

                receiveData = new byte[1024];
                receivePacket = new DatagramPacket(receiveData,
                        receiveData.length);
                serverSocket.receive(receivePacket);
                sentence = new String(receivePacket.getData());
                /*if (sentence != null && !sentence.equals("")) {
                    System.out.println(sentence);
                }*/
                sentence = sentence.trim();
                if (sentence.equals("backup")) {
                    sendPacket = new DatagramPacket(backupServer, backupServer.length, IPAddress, port);
                    serverSocket.send(sendPacket);
                }
            }
        } catch (SocketTimeoutException e) {
            System.out.println("timeout: " + e);
        } catch (SocketException ex) {
            System.out.println("Error Socket: " + ex);
        } catch (IOException e) {
            System.out.println("Error sending packet: " + e);
        }

    }

    public synchronized boolean isShutdown() {
        return shutdown;
    }

    public synchronized void setShutdown(boolean shutdown) {
        this.shutdown = shutdown;
    }
}